# my_server.py
from typing import List
import json
import numpy as np
import matplotlib.pyplot as plt
import requests
from fastmcp import FastMCP
import asyncio # We'll need this later for the client
from apps.cpm.mcp.mcp_db import g_obj_db
from config.app_config import AppConfig as AC
from common.app_manager import AppManager

# Instantiate the server, giving it a name
mcp = FastMCP(name="My First MCP Server")
file_seq = 0
class DrawXYsMcpsFm(object):
    FIRST_RUN = True
    fig = None
    ax = None
    axs = None

    def __init__(self):
        self.name = 'apps.cpm.mcp.draw_x_ys_mcps_fm.DrawXYsMcpsFm'

    @staticmethod
    def draw_curves(img_fn:str, x:np.ndarray, ys:np.ndarray, titles:List, labels:List) -> int:
        if DrawXYsMcpsFm.FIRST_RUN:
            DrawXYsMcpsFm.fig, DrawXYsMcpsFm.ax, DrawXYsMcpsFm.axs = AppManager.init_matplotlib(rows=2, cols=1)
            DrawXYsMcpsFm.FIRST_RUN = False
        # 绘制第一个图（不同RCS）
        DrawXYsMcpsFm.create_radar_plot(
            DrawXYsMcpsFm.fig, DrawXYsMcpsFm.axs[0], 
            x, ys[0],
            title=titles[0],
            labels=titles[0]
        )
        DrawXYsMcpsFm.create_radar_plot(
            DrawXYsMcpsFm.fig, DrawXYsMcpsFm.axs[1], 
            x, ys[1],
            title=titles[1],
            labels=labels[1]
        )
        # 统一调整
        plt.tight_layout()
        plt.savefig(f'./work/files/{img_fn}')
        return 0

    def create_radar_plot(fig, ax, ranges, snr_data, title, labels):
        """创建雷达性能曲线图"""
        ax.plot(ranges, snr_data[0], 'k',      label=labels[0])
        ax.plot(ranges, snr_data[1], 'k-.',    label=labels[1])
        ax.plot(ranges, snr_data[2], 'k:',     label=labels[2])
        
        ax.grid(True, which='both', linestyle='--', alpha=0.7)
        ax.set_xlabel('Detection Range (km)', fontsize=12)
        ax.set_ylabel('SNR (dB)', fontsize=12)
        ax.set_title(title, fontsize=14)
        ax.legend(frameon=True, loc='lower right')
        # ax.set_xlim(ranges[0], ranges[-1])
        # ax.set_ylim(-40, 10)  # 固定y轴范围便于对比




def get_key_obj(key:str) -> bytes:
    url = f'{AC.get_key_obj_url}?key={key}'
    resp = requests.get(url)
    return resp.content

@mcp.tool()
def draw_x_ys(v_keys:str, vs_keys:str, titles_raw:str, labels_raw:str) -> dict:
    global file_seq
    titles = json.loads(titles_raw)
    labels = json.loads(labels_raw)
    v_arrs = v_keys.split(',')
    x_key = v_arrs[0]
    x_obj = get_key_obj(x_key)
    x = np.frombuffer(x_obj, np.float64)
    vs_arrs0 = vs_keys.split(',')
    ys = []
    for vsi in vs_arrs0:
        vs_arrs1 = vs_arrs0[0].split(':')
        ys_num = int(vs_arrs1[1])
        for idx in range(ys_num):
            print(f'@@@ ys_{idx}: ?')
            ys.append(np.frombuffer(get_key_obj(f'{vs_arrs1[0]}_{idx}'), np.float64).reshape(3, 1000))
    print(f'x: {x.shape}; ys: {len(ys)}, num={ys_num}; {ys[0].shape};')
    file_seq += 1
    img_fn = f'img_{file_seq:05d}.png'
    DrawXYsMcpsFm.draw_curves(img_fn, x, ys, titles, labels)
    return {'images': [
        {'img_fn': img_fn}
    ]}

@mcp.tool()
def greet(name: str) -> str:
    """Returns a simple greeting."""
    return f"Hello, {name}!"

@mcp.tool()
def add(a: int, b: int) -> int:
    """Adds two numbers together."""
    return a + b

# my_server.py (continued)
APP_CONFIG = {"theme": "dark", "version": "1.1", "feature_flags": ["new_dashboard"]}

@mcp.resource("data://config")
def get_config() -> dict:
    """Provides the application configuration."""
    return APP_CONFIG

USER_PROFILES = {
    101: {"name": "Alice", "status": "active"},
    102: {"name": "Bob", "status": "inactive"},
}

@mcp.resource("users://{user_id}/profile")
def get_user_profile(user_id: int) -> dict:
    """Retrieves a user's profile by their ID."""
    # The {user_id} from the URI is automatically passed as an argument
    return USER_PROFILES.get(user_id, {"error": "User not found"})

@mcp.prompt("summarize")
async def summarize_prompt(text: str) -> list[dict]:
    """Generates a prompt to summarize the provided text."""
    return [
        {"role": "system", "content": "You are a helpful assistant skilled at summarization."},
        {"role": "user", "content": f"Please summarize the following text:\n\n{text}"}
    ]

print("Prompt 'summarize' added.")

if __name__ == "__main__":
    print("\n--- Starting FastMCP Server via __main__ ---")
    # This starts the server, typically using the stdio transport by default
    mcp.run(transport="streamable-http")